package com.atguigu.edu.realtime.app.dwd.db;

import com.atguigu.edu.realtime.util.MyKafkaUtil;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

//课程域    答题情况统计（一次答题）第16张表  已成功跑通
public class DwdCourseQuestionAnswer {
    public static void main(String[] args) throws Exception {

        // TODO 1. 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);


        // TODO 2. 从 Kafka 读取 topic_db 数据，封装为 Flink SQL 表
        tableEnv.executeSql(MyKafkaUtil.getTopicDbDDL("dwd_course_question_answer"));

        // TODO 3. 读取测验问题表数据，封装为表
        Table testExamQuestion = tableEnv.sqlQuery("select\n" +
                "data['id'] id,\n" +
                "data['user_id'] user_id,\n" +
                "data['question_id'] question_id,\n" +
                "data['is_correct'] is_correct,\n" +
                "date_format(data['create_time'],'yyyy-MM-dd') date_id,\n" +
                "data['create_time'] create_time,\n" +
                "ts\n" +
                "from topic_db\n" +
                "where `table` = 'test_exam_question'\n" +
                "and `type` = 'insert'\n");
        tableEnv.createTemporaryView("test_exam_question",testExamQuestion);

        // TODO 4. 建立 Upsert-Kafka dwd_course_question_answer 表
        tableEnv.executeSql("create table dwd_course_question_answer (\n" +
                "id string,\n" +
                "user_id string,\n" +
                "question_id string,\n" +
                "is_correct string,\n" +
                "date_id string,\n" +
                "create_time string,\n" +
                "ts string,\n" +
                "primary key(id) not enforced\n" +
                ")" + MyKafkaUtil.getUpsertKafkaDDL("dwd_course_question_answer"));

        // TODO 5. 将数据写入 Upsert-Kafka 表
        tableEnv.executeSql("" +
                "insert into dwd_course_question_answer select * from test_exam_question");

    }
}

